﻿@page "/Admin/TaskManager"
@using Longbow.Tasks
@using JxAudio.Web.Vo
@using System.Diagnostics.CodeAnalysis
@using Microsoft.Extensions.Localization

@inject IStringLocalizer<TaskManager> TaskManagerLocalizer
@inject ToastService ToastService

<AdminTable TItem="ScheduleVo" Items="ScheduleVos" ShowExtendButtons="true" ShowExtendDeleteButton="false" ShowExtendEditButton="false">
    <TableColumns>
        <TableColumn @bind-Field="@context.Name"></TableColumn>
        <TableColumn @bind-Field="@context.Status"></TableColumn>
        <TableColumn @bind-Field="@context.NextRuntime"></TableColumn>
        <TableColumn @bind-Field="@context.LastRuntime"></TableColumn>
        <TableColumn @bind-Field="@context.LastRunResult"></TableColumn>
        <TableColumn @bind-Field="@context.CreatedTime"></TableColumn>
    </TableColumns>
    <RowButtonTemplate>
        <TableCellButton Text="@TaskManagerLocalizer["Run"]" IsDisabled="context.LastRunResult == TriggerResult.Running" OnClick="() => RunNow(context)"></TableCellButton>
        <TableCellButton 
            Text="@(context.Status == SchedulerStatus.Disabled ? TaskManagerLocalizer["Start"] : TaskManagerLocalizer["Stop"])"
            OnClick="() => ChangeStatus(context)"
            Color="Color.Danger"
            ></TableCellButton>
    </RowButtonTemplate>
</AdminTable>

@code {

    [NotNull]
    public List<ScheduleVo>? ScheduleVos { get; set; }
    
    protected override void OnInitialized()
    {
        base.OnInitialized();
        Notify();
    }
    
    private void Notify()
    {
        ScheduleVos = TaskServicesManager.ToList().Select(x => new ScheduleVo()
        {
            CreatedTime = x.CreatedTime,
            LastRunResult = x.LastRunResult,
            LastRuntime = x.LastRuntime,
            Name = x.Name,
            NextRuntime = x.NextRuntime,
            Status = x.Status,
            Scheduler = x
        }).ToList();
    }

    private async Task RunNow(ScheduleVo scheduleVo)
    {
        _ = scheduleVo.Scheduler!.Run();
        await ToastService.Success(TaskManagerLocalizer["Success"], TaskManagerLocalizer["SuccessContent"]);
    }

    private void ChangeStatus(ScheduleVo scheduleVo)
    {
        if (scheduleVo.Scheduler != null)
        {
            scheduleVo.Scheduler.Status = scheduleVo.Status == SchedulerStatus.Disabled 
                ? SchedulerStatus.Running : SchedulerStatus.Disabled;
            Notify();
        }
        
    }

}